package com.kgc.order.service.impl;

import com.kgc.dao.TbOrderItemMapper;
import com.kgc.dao.TbOrderMapper;
import com.kgc.entity.TbItem;
import com.kgc.entity.TbOrder;
import com.kgc.entity.TbOrderItem;
import com.kgc.entity.TbOrderShipping;
import com.kgc.order.jedis.JedisClient;
import com.kgc.order.service.OrderService;
import com.kgc.utils.IDUtils;
import com.kgc.utils.ItripResult;
import com.kgc.utils.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;


@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private JedisClient jedisClient;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;


    @Override
    public ItripResult createOrder(Order order) {
        String idString = jedisClient.get("ORDERID");
        if (StringUtils.isEmpty(idString)){
            idString=System.currentTimeMillis()+"";
            jedisClient.set("ORDERID",idString);
        }
        Long orderId = jedisClient.incr("ORDERID");
        TbOrder tbOrder=new TbOrder();
        tbOrder.setOrderId(orderId+"");//设置订单编号
        tbOrder.setPayment(order.getPayment());
        tbOrder.setPaymentType(order.getPayType());
        tbOrder.setPostFee(0+"");
        tbOrder.setStatus(1);
  /*      tbOrder.setUserId();*/
        tbOrder.setCreateTime(new Date());
        tbOrder.setUpdateTime(new Date());

        tbOrderMapper.insertSelective(tbOrder);
        TbOrderItem orderItem=null;
        for (int i = 0; i <order.getOrderItems().size(); i++) {
            //购物车中的每一个商品
            TbItem item=order.getOrderItems().get(i);
            orderItem=new TbOrderItem();
            //生成明细的编号
            orderItem.setId(IDUtils.genItemId()+"");
            //订单的编号
            orderItem.setOrderId(orderId+"");
            //商品编号
            orderItem.setItemId(item.getId()+"");
            //商品的名称
            orderItem.setTitle(item.getTitle());
            //这个商品总金额
            orderItem.setTotalFee(item.getPrice()*item.getNum());
            //商品价格
            orderItem.setPrice(item.getPrice());
            //商品购数量
            orderItem.setNum(item.getNum());
            orderItem.setPicPath(item.getImage());
            tbOrderItemMapper.insertSelective(orderItem);
        }
        TbOrderShipping tbOrderShipping =order.getOrderShipping();
        tbOrderShipping.setOrderId(orderId+"");
        tbOrderShipping.setCreated(new Date());
        tbOrderShipping.setReceiverAddress("孝感");
        tbOrderShipping.setReceiverPhone("183930982");
        tbOrderShipping.setReceiverName("李四");

        return ItripResult.build(200,"ok",orderId);
    }
}
